/*
 * @Author: xiaosihan
 * @Date: 2024-10-02 14:09:50
 * @Last Modified by: xiaosihanosihan
 * @Last Modified time: 2025-08-29 21:16:04
 */
import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import cloneDeep from 'lodash/cloneDeep';
import Taro from '@tarojs/taro';
import { GoodsBaseData, GoodsData } from 'types/type';
import utils from './utils';
class GoodsUtils {
    keys = [
        'colors',
        'component',
        'mockupUrls',
        'miniProgramMockupUrls',
        'size',
        'sizeInfo',
        'thumbs',
        'sizePrice',
    ];
    //将 商品数据中的 json 字符串转成json格式
    tojson(goodsData: any): GoodsData {
        const newGoodsData = cloneDeep(goodsData);
        this.keys.map((key) => {
            let value = {};
            do {
                value = newGoodsData[key];
                if (isString(value)) {
                    newGoodsData[key] = JSON.parse(value as string);
                }
            } while (isString(value));
        });
        return newGoodsData;
    }

    //将 商品数据中的 json 转成json字符串
    toString(goodsData) {
        const newGoodsData = cloneDeep(goodsData);
        this.keys.map((key) => {
            const value = newGoodsData[key];
            if (isObject(value)) {
                newGoodsData[key] = JSON.stringify(value);
            }
        });
        return newGoodsData;
    }

    // 获取本地缓存的图片地址
    async getCache(url) {
        const originUrl = `https:${url.replace(/^https?:/, '')}`;
        // 读取数据
        let localPath = await new Promise(async (resolve, reject) => {
            let localPath = Taro.getStorageSync(originUrl);
            if (!localPath) {
                //本地图片地址
                const res = await Taro.downloadFile({
                    url: originUrl,
                });
                localPath = res.tempFilePath;
                // 存储数据
                Taro.setStorageSync(originUrl, localPath);
            }
            resolve(localPath);
        });
        return localPath;
    }

    //获取svg的宽高
    getSvgSize(svgContent: string): { width: number; height: number } {
        // 2. 解析宽高
        const widthMatch = svgContent.match(/<svg[^>]*width=["']([^"']*)["']/i)![1];
        const heightMatch = svgContent.match(/<svg[^>]*height=["']([^"']*)["']/i)![1];
        const viewBoxMatch = svgContent.match(/<svg[^>]*viewBox=["']([^"']*)["']/i)![1];

        // 3. 优先从 width/height 提取，若无则取 viewBox 后两个值
        let width: number | string = widthMatch ? widthMatch : '';
        let height: number | string = heightMatch ? heightMatch : '';

        // 4. 如果 width/height 不存在，尝试从 viewBox 解析
        if (!width || !height) {
            const viewBoxValues = viewBoxMatch ? viewBoxMatch.split(/[\s,]+/) : [];
            console.log('viewBoxValues', viewBoxValues);
            if (viewBoxValues.length >= 4) {
                width = viewBoxValues[2]; // viewBox 格式: "0 0 width height"
                height = viewBoxValues[3];
            }
        }

        // 5. 去除单位（如 "100px" → 100）
        width = width ? parseFloat(width.replace(/[^\d.]/g, '')) : 0;
        height = height ? parseFloat(height.replace(/[^\d.]/g, '')) : 0;
        return { width, height };
    }

    //获取某个部位的uv图,格式是svg
    get_uv_url(goodsBaseData: GoodsBaseData, componentKey: string) {
        const { model_size, components } = goodsBaseData.data;
        const component = components.find((item) => item.key === componentKey)!;
        let uv_url = component[`uv_${model_size}` as keyof GoodsBaseData["data"]["components"][0]] as string ||
            component.uv_110 ||
            component.uv_120 ||
            component.uv_130 ||
            component.uv_140 ||
            component.uv_150 ||
            component.uv_160 ||
            component.uv_3XS ||
            component.uv_2XS ||
            component.uv_XS ||
            component.uv_S ||
            component.uv_M ||
            component.uv_L ||
            component.uv_XL ||
            component.uv_2XL ||
            component.uv_3XL ||
            component.uv_4XL ||
            component.uv_5XL ||
            component.uv_6XL ||
            component.uv_7XL ||
            component.uv_8XL ||
            component.uv_9XL ||
            component.uv_10XL ||
            "";
        return uv_url;
    }

    // 尺寸请求中
    sizeLoading = false;

    // 尺寸缓存
    sizeMap = new Map<string, { width: number, height: number }>();

    //计算指定板片的宽高 //传入商品的component
    async computerComponentSize(goodsBaseData: GoodsBaseData, componentKey: string) {
        let uv_url = this.get_uv_url(goodsBaseData, componentKey);

        // 有缓存就返回缓存
        if (this.sizeMap.has(uv_url)) {
            return this.sizeMap.get(uv_url)!;
        }

        console.log('uv_url', uv_url);

        while (this.sizeLoading) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }

        // 有缓存就返回缓存
        if (this.sizeMap.has(uv_url)) {
            return this.sizeMap.get(uv_url)!;
        }

        this.sizeLoading = true;


        return new Promise<{ width: number, height: number }>(async (resolve, reject) => {
            // 1. 发起请求获取 SVG 内容
            Taro.request({
                url: utils.ossSuffix(uv_url),
                success: (res) => {
                    if (res.statusCode === 200) {
                        let svgText = res.data;
                        const { width, height } = this.getSvgSize(svgText);
                        this.sizeMap.set(uv_url, { width, height });
                        resolve({ width, height });
                        this.sizeLoading = false;
                    }
                },
                fail: (err) => {
                    console.log('err', err);
                    // reject(err);
                }
            });
        });
    }

}
const goodsUtils = new GoodsUtils();
export default goodsUtils;
